package com.kobe.game_40;


/**
 * 
 * The decimal number, 585 = 1001001001[2] (binary), is palindromic in both
 * bases.
 * 
 * Find the sum of all numbers, less than one million, which are palindromic in
 * base 10 and base 2.
 * 
 * (Please note that the palindromic number, in either base, may not include
 * leading zeros.)
 * 
 *  the answer is :872187
 */
public class Game36 {

    public static void main(String[] args) {
        int bd = 0;

        for (int i = 0; i < 1000000; i++) {
            if (isPalidnromic(String.valueOf(i))
                    && isPalidnromic(Integer.toBinaryString(i))) {
                bd += i;
            }
        }
        System.out.println(bd);

    }

    private static boolean isPalidnromic(String number) {
        CharSequence pre;
        CharSequence beh;
        if (number.length() % 2 == 0) {
            pre = number.subSequence(0, number.length() / 2);
            beh = number.subSequence(number.length() / 2, number.length());

            return comparePalidnromic(pre, beh);

        } else {
            pre = number.subSequence(0, number.length() / 2);
            beh = number.subSequence(number.length() / 2 + 1, number.length());

            return comparePalidnromic(pre, beh);
        }
    }

    private static boolean comparePalidnromic(CharSequence cs1, CharSequence cs2) {
        int length = cs1.length();
        for (int i = 0; i < length; i++) {
            if (cs1.charAt(i) != cs2.charAt(length - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}
